package com.boot.security.server.dict.service.impl;

import com.boot.security.server.common.Result;
import com.boot.security.server.common.ResultBuilder;
import com.boot.security.server.contant.Constant;
import com.boot.security.server.dict.enums.DictEnum;
import com.boot.security.server.dict.mapper.DataDictDetailsMapper;
import com.boot.security.server.dict.mapper.DataDictMapper;
import com.boot.security.server.dict.model.DataDict;
import com.boot.security.server.dict.model.DataDictDetails;
import com.boot.security.server.dict.model.LayUiModel;
import com.boot.security.server.dict.service.IDictService;
import com.boot.security.server.dict.vo.DataDictVo;
import com.boot.security.server.dto.LoginUser;
import com.boot.security.server.mapper.SysRoleUserMapper;
import com.boot.security.server.model.domain.SysRoleUser;
import com.boot.security.server.user.mapper.SysUserMapper;
import com.boot.security.server.user.model.SysUser;
import com.boot.security.server.utils.BeanHelper;
import com.boot.security.server.utils.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 字典业务实现
 * @author Administrator
 */
@SuppressWarnings("ALL")
@Service
@Slf4j
public class DictServiceImpl implements IDictService {

    @Autowired
    private DataDictMapper dictMapper;
    @Autowired
    private DataDictDetailsMapper detailsMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleUserMapper roleUserMapper;

    @Override
    public LayUiModel findAllPage (HttpServletRequest request) {
        Integer page = Integer.valueOf(request.getParameter("page"));
        Integer limit = Integer.valueOf(request.getParameter("limit"));
        Integer index = (page - 1) * limit;
        List<DataDictVo> vos = new ArrayList<>();
        int count = dictMapper.count();
        if (count > 0) {
            List<DataDict> dicts = dictMapper.findAll(index, limit);
            dicts.forEach(dict -> {
                DataDictVo vo = BeanHelper.copyProperties(dict, DataDictVo.class);
                List<DataDictDetails> details = detailsMapper.queryByDictId(dict.getId());
                if (details.size() == 0) {
                    vo.setNext(0);
                } else {
                    Optional<DataDictDetails> op = details.stream().max(Comparator.comparingInt(DataDictDetails::getDataKey));
                    DataDictDetails max = op.get();
                    vo.setNext(max.getDataKey());
                }
                vos.add(vo);
            });
            return new LayUiModel(count, vos);
        }
        return new LayUiModel(0, vos);
    }

    @Override
    public LayUiModel findById (Integer id) {
        DataDict dict = dictMapper.findById(id);
        List<DataDictVo> vos = new ArrayList<>();
        DataDictVo vo = BeanHelper.copyProperties(dict, DataDictVo.class);
        vos.add(vo);
        return new LayUiModel(1, vos);
    }

    @SuppressWarnings("rawtypes")
    @Override
    public Result add (DataDict dataDict) {
        String code = dataDict.getCode();
        boolean isWord = code.matches("^[A-Za-z]+$");
        if (! isWord) {
            return ResultBuilder.systemError("编号只能输入英文！");
        }
        int c = dictMapper.findByCode(code);
        if (c > 0) {
            return ResultBuilder.systemError("编号已存在！");
        }
        int n = dictMapper.findByName(dataDict.getName());
        if (n > 0) {
            return ResultBuilder.systemError("名称已存在！");
        }
        int i = dictMapper.add(dataDict);
        if (i > 0) {
            return ResultBuilder.success();
        }
        log.info("字典新增");
        return ResultBuilder.systemError("新增数据字典失败！");
    }

    @Override
    public Result delete (Integer id) {
        List<DataDictDetails> list = detailsMapper.queryByDictId(id);
        if (CollectionUtils.isNotEmpty(list)) {
            return ResultBuilder.systemError("该字典下有字典详情,无法删除！");
        }
        int i = dictMapper.delete(id);
        if (i > 0) {
            return ResultBuilder.success();
        }
        log.info("字典删除");
        return ResultBuilder.systemError("删除数据字典失败！");
    }

    @Override
    public Result update (DataDict dataDict) {
        String code = dataDict.getCode();
        Integer id = dataDict.getId();
        boolean isWord = code.matches("^[A-Za-z]+$");
        if (! isWord) {
            return ResultBuilder.systemError("编号只能输入英文！");
        }
        int c = dictMapper.findByCodeAndId(code, id);
        if (c > 0) {
            return ResultBuilder.systemError("编号已存在！");
        }
        int n = dictMapper.findByNameAndId(dataDict.getName(), id);
        if (n > 0) {
            return ResultBuilder.systemError("名称已存在！");
        }
        DataDict dict = dictMapper.findById(id);
        dict.setCode(code);
        dict.setName(dataDict.getName());
        int i = dictMapper.update(dict);
        if (i > 0) {
            return ResultBuilder.success();
        }
        log.info("字典修改");
        return ResultBuilder.systemError("修改数据字典失败！");
    }

    @Override
    public List<Map<String, Object>> findBranchByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.公司.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        detailsList.forEach(details -> {
            Map<String, Object> map = new HashMap<>();
            map.put("key", details.getDataKey());
            map.put("value", details.getDataValue());
            stringList.add(map);
        });

        return stringList;
    }

    @Override
    public List<Map<String, Object>> findOverseeFormByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.督察形式.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        detailsList.forEach(details -> {
            Map<String, Object> map = new HashMap<>();
            map.put("value", details.getDataValue());
            stringList.add(map);
        });
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findQuestionByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.问题类别.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        detailsList.forEach(details -> {
            Map<String, Object> map = new HashMap<>();
            map.put("value", details.getDataValue());
            stringList.add(map);
        });
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findQuestionKeywordByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.问题关键字.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        detailsList.forEach(details -> {
            Map<String, Object> map = new HashMap<>();
            map.put("value", details.getDataValue());
            stringList.add(map);
        });
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findScheduleByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.整改进度.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(detailsList)) {
            detailsList.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("value", details.getDataValue());
                stringList.add(map);
            });
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findSourceProblemByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.问题来源.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(detailsList)) {
            detailsList.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("value", details.getDataValue());
                stringList.add(map);
            });
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findReviewerByCode () {
        LoginUser loginUser = UserUtil.getLoginUser();
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (loginUser.getId() != null) {
            SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
            if (! StringUtils.equals(user.getUsername(), "xtadmin")) {
                SysUser sysUser = userMapper.selectByPrimaryKey(user.getUserId());
                Map<String, Object> map = new HashMap<>();
                map.put("key", sysUser.getId());
                map.put("value", sysUser.getUsername());
                stringList.add(map);
            }
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findSexByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.性别.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(detailsList)) {
            detailsList.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("key", details.getDataKey());
                map.put("value", details.getDataValue());
                stringList.add(map);
            });
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findYearByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.年份.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(detailsList)) {
            detailsList.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("value", details.getDataValue());
                stringList.add(map);
            });
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findStatusByCode () {
        List<DataDictDetails> detailsList = dictMapper.findDictDetailsByCode(DictEnum.状态.getCode());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(detailsList)) {
            detailsList.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("key", details.getDataKey());
                map.put("value", details.getDataValue());
                stringList.add(map);
            });
        }
        return stringList;
    }

    /**
     *
     **/
    @Override
    public List<Map<String, Object>> getOversee () {
        List<Map<String, Object>> stringList = new ArrayList<>();
        List<SysUser> oversee = dictMapper.getOversee(Constant.DBADMIN);
        if (CollectionUtils.isNotEmpty(oversee)) {
            oversee.forEach(details -> {
                Map<String, Object> map = new HashMap<>();
                map.put("key", details.getId());
                map.put("value", details.getNickname());
                stringList.add(map);
            });
        }

        return stringList;
    }

    @Override
    public List<Map<String, Object>> findUser () {
        List<SysUser> users = userMapper.selectAll();
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(users)) {
            for (SysUser user : users) {
                if (! StringUtils.equals(user.getUsername(), "xtadmin")) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("key", user.getId());
                    map.put("value", user.getNickname());
                    stringList.add(map);
                }
            }
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> getUserName () {
        List<SysUser> users = userMapper.selectAll();
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(users)) {
            for (SysUser user : users) {
                if (! StringUtils.equals(user.getUsername(), "xtadmin")) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("key", user.getId());
                    map.put("value", user.getUsername());
                    stringList.add(map);
                }
            }
        }
        return stringList;
    }

    @Override
    public List<Map<String, Object>> findBranchByCodeAndUserId () {
        LoginUser loginUser = UserUtil.getLoginUser();
        SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
        List<Map<String, Object>> stringList = new ArrayList<>();
        if (StringUtils.isNotBlank(user.getBranch())) {
            List<String> ss = Arrays.asList(user.getBranch().split(","));
            ss.forEach(branch -> {
                String value = detailsMapper.findDataValueByDataKeyAndDictId(branch, 3);
                Map<String, Object> map = new HashMap<>();
                map.put("key", branch);
                map.put("value", value);
                stringList.add(map);
            });
        }
        return stringList;
    }

    @Override
    public List<String> findBranchByUserIdAndCode () {
        LoginUser loginUser = UserUtil.getLoginUser();
        SysUser user = userMapper.selectByPrimaryKey(loginUser.getId());
        List<String> ss = Arrays.asList(user.getBranch().split(","));
        List<String> stringList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(ss)) {
            ss.forEach(branch -> {
                String value = detailsMapper.findDataValueByDataKeyAndDictId(branch, 3);
                stringList.add(value);
            });
        }
        return stringList;
    }
}
